﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LIMS.Service;
using LIMS.Entities;
using Castle.Core.Logging;

namespace LIMS.Shared
{
    public class DefaultPagePresenter : BasePresenter<IDefaultPageView>
    {
        private IDefaultPageView view;
        private IUserManagementService userService;
        private IGroupManagementService groupService;
        private ILogger logger;
        private IMailService mailService;
        public DefaultPagePresenter(IDefaultPageView view, ILogger oLogger, IUserManagementService myUserService,
            IGroupManagementService mygroupService, IMailService oMail)
            : base(view)
        {
            this.view = view;
            this.logger = oLogger;
            this.userService = myUserService;
            this.groupService = mygroupService;
            this.mailService = oMail;
        }

        /// <summary>
        /// Updates user last login IP and datetime.
        /// </summary>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public bool UpdateUser()
        {
            try
            {
                userService.Save(view.CurrentUser);
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("Error while updating user.", ex);
                return false;
            }
        }

        /// <summary>
        /// Resets user password.
        /// </summary>
        /// <param name="sEmailAddress"></param>
        /// <returns></returns>
        public bool SendResetPasswordRequest(string sEmailAddress, string sUrl)
        {
            try
            {
                //See if vaild Email
                if (ValidateEmail(sEmailAddress))
                {
                    //Now check captcha
                    if (!view.CheckCaptch())
                    {
                        view.ErrorMessage = "Code does not match, please try again!";
                        return false;
                    }
                    //Get user with this Email address
                    User thisUser = userService.GetUserByEmailAddress(sEmailAddress.Trim());
                    if (thisUser != null)
                    {
                        //Try resetting password
                        if (userService.ResetUserPassword(thisUser, sUrl))
                        {
                            view.ErrorMessage = "Password resent instructions have been sent to your Email address.";
                            return true;
                        }
                        else
                        {
                            view.ErrorMessage = "Error occured while resetting password.Please contact your administrator.";
                            return false;
                        }
                    }
                    else
                    {
                        view.ErrorMessage = "No user Email address in system : " + sEmailAddress;
                        return false;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                logger.Error("Error occured while password reset request.", ex);
                return false;
            }
        }
        /// <summary>
        /// Resets user password
        /// </summary>
        /// <param name="sPassword"></param>
        /// <param name="sConfirmPassword"></param>
        /// <returns></returns>
        public bool ResetUserPassword(string sPassword, string sConfirmPassword)
        {
            //Validate passwords.
            if (sPassword.Trim() == sConfirmPassword.Trim())
            {
                if (sPassword.Trim().Length == 0 || sConfirmPassword.Trim().Length == 0)
                {

                    view.ShowMessage(MessageType.Error, Resource.ERROR_PASSWORD_EMPTY);
                    //view.ErrorMessage = Resource.ERROR_PASSWORD_EMPTY;
                    return false;
                }
            }
            else
            {
                view.ShowMessage(MessageType.Error, Resource.ERROR_PASSWORD_NO_MATCH);
                // view.ErrorMessage = Resource.ERROR_PASSWORD_NO_MATCH;
                return false;
            }

            try
            {
                //Make sure user is available
                if (view.CurrentUser != null)
                {
                    //Encrypt password.
                    view.CurrentUser.Password = Resource.GenerateSHAPasswordHash(sPassword.Trim());
                    //Clear reset hash.
                    view.CurrentUser.ResetPasswordHash = string.Empty;
                    view.CurrentUser.ResetPasswordDateTime = DateTime.Now;
                    //Save it.
                    userService.Save(view.CurrentUser);
                    return true;
                }
                else
                {
                    logger.Error("User was null in ResetUserPassword");
                    return false;
                }

            }
            catch (Exception ex)
            {
                logger.Error("Error occured while resetting password", ex);
                return false;
            }
        }

        /// <summary>
        /// Validate Email address
        /// </summary>
        /// <param name="Email"></param>
        /// <returns></returns>
        public bool ValidateEmail(string Email)
        {
            if (Email.Trim().Length == 0)
            {
                view.ShowMessage(MessageType.Error, "Please enter email address.");
                //  view.ErrorMessage = "Please enter email address.";
                return false;
            }
            else
            {
                if (!Resource.IsValidEmail(Email))
                {
                    view.ShowMessage(MessageType.Error, "Please enter valid email address.");
                    //view.ErrorMessage = "Please enter valid email address";
                    return false;
                }
                return true;
            }
        }
        /// <summary>
        /// Checking for super user
        /// </summary>
        /// <param name="sUserID"></param>
        /// <param name="sPassword"></param>
        /// <param name="bFocusOn"></param>
        /// <returns></returns>
        public bool SuperAdminCheck(string sUserID, string sPassword, out bool bFocusOn)
        {
            if (sUserID.Trim().Length == 0)
            {
                view.ShowMessage(MessageType.Error, "User name mandatory");
                //    view.ErrorMessage = "User name mandatory";
                bFocusOn = false; //False for User Textbox
                return false;
            }
            if (sPassword.Trim().Length == 0)
            {
                view.ShowMessage(MessageType.Error, "Password mandatory");
                //view.ErrorMessage = "Password mandatory";
                bFocusOn = true; //true for password Textbox
                return false;
            }

            string sUserId = Resource.ReadValueFromConfigration("SuperUserName");
            string sUserPassword = Resource.ReadValueFromConfigration("SuperUserPassword");
            if ((!string.IsNullOrEmpty(sUserId)) && (!string.IsNullOrEmpty(sUserPassword)))
            {
                if ((sUserID.Trim().ToUpper().Equals(sUserId.Trim().ToUpper())) && (sPassword.Trim().ToUpper().Equals(sUserPassword.Trim().ToUpper())))
                {
                    bFocusOn = false;
                    return true;
                }
            }
            bFocusOn = false;
            return false;
        }
        /// <summary>
        /// Validates user
        /// </summary>
        /// <param name="sUserID"></param>
        /// <param name="sPassword"></param>
        /// <returns></returns>
        public bool ValidateUser(string sUserID, string sPassword, out bool bFocusOn, string sIPAddress)
        {
            if (sUserID.Trim().Length == 0)
            {
                view.ShowMessage(MessageType.Error, "User name mandatory");
                //    view.ErrorMessage = "User name mandatory";
                bFocusOn = false; //False for User Textbox
                return false;
            }
            if (sPassword.Trim().Length == 0)
            {
                view.ShowMessage(MessageType.Error, "Password mandatory");
                //view.ErrorMessage = "Password mandatory";
                bFocusOn = true; //true for password Textbox
                return false;
            }

            view.CurrentUser = userService.GetUserByUserID(sUserID);
            if (view.CurrentUser == null)
            {
                view.ShowMessage(MessageType.Error, "Invalid login details (" + sUserID + ")");
                bFocusOn = false; //False for User Textbox
                return false;
            }
            bFocusOn = true;
            return true;
        }

        /// <summary>
        /// Handles query string request
        /// </summary>
        /// <param name="passwordResetHash"></param>
        /// <returns></returns>
        public bool HandleProbablePasswordResetRequest(string passwordResetHash)
        {
            try
            {
                //Gets any user with such HASH
                User oUser = userService.GetUserByPasswordResetHash(passwordResetHash);
                if (oUser != null)
                {
                    //If found, set it as current user.
                    view.CurrentUser = oUser;
                    return true;
                }
                else
                {
                    //No such user.
                    logger.Debug("No user with password reset hash: " + passwordResetHash);
                    return false;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error while handling password reset request. ", ex);
                return false;
            }

        }
        /// <summary>
        /// Getting All Permission Types
        /// </summary>
        /// <param name="iUserId"></param>
        /// <returns></returns>
        public List<string> GetUserPermissionType(int iUserId)
        {
            List<string> sPremissionType = new List<string>();
            List<GroupUserLink> oGroupUserLinkList = new List<GroupUserLink>();
            List<GroupPermissionLink> oGroupPermissionLinkList = new List<GroupPermissionLink>();
            try
            {
                oGroupUserLinkList = userService.GetUserLinkGroupIdByGroupUserLinkUserId(iUserId);
                foreach (GroupUserLink oGroupUserLink in oGroupUserLinkList)
                {
                    oGroupPermissionLinkList = userService.GetUserLinkPermissionLinksByGroupId(oGroupUserLink.GroupId);
                    foreach (GroupPermissionLink oGPL in oGroupPermissionLinkList)
                    {
                        sPremissionType.Add(oGPL.PermissionId.ToString());
                    }
                }
                // sPremissionType = oGPL.PermissionId.ToString();
                return sPremissionType;
            }
            catch (Exception ex)
            {
                logger.Error("Error in Getting User Permission Type", ex);
            }
            return sPremissionType;
        }

    }
}
